const express = require('express')
const app = express()
const { createBundleRenderer } = require('vue-server-renderer')
const path = require('path')
const template = require('fs').readFileSync('./index.template.html', 'utf-8')
const serverBundle = require('./dist/vue-ssr-server-bundle.json')
const clientManifest = require('./dist/vue-ssr-client-manifest.json')

const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false, // 推荐
  template,
  clientManifest
})
// 引入静态文件  否则运行报错
app.use('/js', express.static(path.resolve(__dirname, './dist/js')))
app.use('/img', express.static(path.resolve(__dirname, './dist/img')))
app.use('/css', express.static(path.resolve(__dirname, './dist/css')))
app.get(['/', '/about'], (req, res) => {
  const context = {
    title: 'ssr demo====',
    meta: '',
    url: req.url
  }
  renderer.renderToString(context, (err, html) => {
    if (err) {
      if (err.code === 404) {
        res.status(404).end('Page not found')
      } else {
        res.status(500).end('Internal Server Error'+err.stack)
      }
    } else {
      res.end(html)
    }
  })

})
app.listen(8080, () => {
  console.log('已监听 localhost:8080')
})
